const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const { protect } = require('../middleware/auth');

/**
 * @route   GET /api/test/db-connection
 * @desc    测试数据库连接并返回状态信息
 * @access  Public
 */
router.get('/db-connection', async (req, res) => {
  try {
    // 检查数据库连接状态
    const dbState = mongoose.connection.readyState;
    let status = '';
    
    switch (dbState) {
      case 0:
        status = '断开连接';
        break;
      case 1:
        status = '已连接';
        break;
      case 2:
        status = '正在连接';
        break;
      case 3:
        status = '正在断开连接';
        break;
      default:
        status = '未知状态';
    }
    
    // 获取数据库统计信息
    let collections = {};
    if (dbState === 1) {
      // 只有在连接状态下才获取集合统计信息
      const collectionNames = (await mongoose.connection.db.listCollections().toArray()).map(c => c.name);
      
      // 获取每个集合的文档数量
      for (const name of collectionNames) {
        const count = await mongoose.connection.db.collection(name).countDocuments();
        collections[name] = count;
      }
    }
    
    res.json({
      success: true,
      message: `数据库连接测试成功，状态: ${status}`,
      data: {
        connectionState: status,
        dbName: mongoose.connection.name,
        host: mongoose.connection.host,
        port: mongoose.connection.port,
        collections: collections
      }
    });
  } catch (error) {
    console.error('数据库连接测试错误:', error);
    res.status(500).json({
      success: false,
      message: '数据库连接测试失败',
      error: error.message
    });
  }
});

module.exports = router; 